import asyncio
from wxauto import WeChat
from tools.log_handler import logger

class WxautoHandler:
    def __init__(self, message_queue):
        self.wx = WeChat()
        self.queue = message_queue
        logger.info("WxautoHandler 初始化完成")
    
    async def send_message(self, user, reply):
        """异步发送消息"""
        self.wx.SendMsg(reply, user)
        logger.info(f"已回复 {user}: {reply}")
        print(f"已回复: {reply}")
    
    async def listen_and_reply_forever(self, listen_list=None):
        interval=1 # 间隔
        if listen_list is None:
            listen_list = ['A一', 'A李']  # 默认多用户
        
        # 获取当前会话列表，确保监听对象有效
        await asyncio.sleep(1)  # 等待微信加载

        valid_listeners = [who for who in listen_list]
        # 添加监听对象
        for who in valid_listeners:
            self.wx.AddListenChat(who=who)
            logger.info(f"已添加监听: {who}")

        logger.info(valid_listeners)
        if not valid_listeners:
            logger.info("没有有效的监听对象，请检查好友名")
            print("没有有效的监听对象，请检查好友名")
            return
        
        logger.info(f"开始监听微信好友消息（仅限以 #ZM 开头），监听: {valid_listeners}")
        print(f"开始监听微信好友消息（仅限以 #ZM 开头），监听: {valid_listeners}")
        
        while True:
            try:
                # 获取所有消息，而不是只监听单一聊天
                # messages = self.wx.GetAllNewMessage()
                messages = self.wx.GetListenMessage()
                # print(111,messages)
                for chat in messages:
                    who = chat.who
                    one_msgs = messages.get(chat)

                    for msg in one_msgs:
                        print(msg)
                        if who in valid_listeners and msg.type == "friend" and msg.content.startswith("#ZM"):
                            content = msg.content
                            logger.info(f"【{who}】: {content}")
                            print(f"【{who}】: {content}")
                            user_input = content[3:].strip()
                            if user_input:
                                await self.queue.add_message(who, user_input, self.send_message)
                await asyncio.sleep(interval)
            
            except Exception as e:
                logger.error(f"监听出错: {e}")
                print(f"监听出错: {e}，继续运行...")
                await asyncio.sleep(interval)